import java.util.Scanner;

/*开发一个新的猜数字小游戏，同时练习使用JUnit来进行单元测试已保证程序的质量。*/
public class NGuessNumber {
    Scanner scanner = new Scanner(System.in);
    int [] answers = new int[4];
    int [] guesses = new int[4];
    int[] count = new int[2];

    //随机生成4个0-9之间的不重复的整型数作为答案并返回
    public int[] generateAnswer() {
        int i = 0;
        while (i<4){
            int answer = (int)(Math.random()*10);
            boolean same = false;
            int j = 0;
            while (j<i){
                if (answer == answers[j]){
                    same = true;
                    break;
                }
                j++;
            }
            if (!same){
                answers[j] = answer;
                i++;
            }
        }
        return answers;
    }

    //接收玩家输入的4个数字并返回。
    public void getPlayerInput(){
        int i = 0;
        while (i<4){
            try{
                System.out.println("请输入第"+(i+1)+"个数字");
                try {
                    guesses[i] = scanner.nextInt();
                }catch (Exception e){
                    scanner.next();
                    System.out.println("请输入数字!");
                    continue;
                }
                i++;
            }catch (Exception e){
                scanner.next();
                System.out.println("请重新输入数字");
                continue;
            }
        }
    }

    //比较玩家猜测和答案后返回提示信息
    public void compareGuessAnswer(){
        int A=0;
        int B=0;
        for (int i=0;i<answers.length;i++){
            for (int j=0;j<guesses.length;j++){
                if (i==j && answers[i]==guesses[j]){
                    A++;
                }else if(answers[i]==guesses[j]){
                    B++;
                }
            }
        }
        count[0] = A;
        count[1] = B;
        System.out.println("A:"+A+"B:"+B);
    }
    //根据提示信息中A的数量判断玩家是否获胜
    public boolean isWin(){
        if (count[0]==4){
            return true;
        }else {
            return false;
        }
    }

    public static void main(String[] args) {
        NGuessNumber nGuessNumber = new NGuessNumber();
        boolean is = true;
        while (is){
            nGuessNumber.generateAnswer();
            while (true){
                nGuessNumber.getPlayerInput();
                nGuessNumber.compareGuessAnswer();
                if (nGuessNumber.isWin()){
                    System.out.println("获胜!");
                    break;
                }
            }
            System.out.println("是否继续！1：继续（输入1） ；2：结束（输入1以外的）");
            int a = 0;
            try {
                a = nGuessNumber.scanner.nextInt();
            }catch (Exception e){
            }
            if (a!=1){
                break;
            }
        }
    }
}
